﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace QuickDev.Common.Data.Sort
{
    public class DynamicPropertySort
    {
        //This is just to get the property info using reflection.  In order to get the value
        //from a property dynamically, we need the property info from the class
        public static PropertyInfo[] GetInfo<K>( K item ) where K : class
        {
            PropertyInfo[] propertyList;
            Type typeInfo;

            typeInfo = item.GetType();
            propertyList = typeInfo.GetProperties();

            return propertyList;
        }

        //This is the dynamic order by func that the OrderBy method needs to work
        public static IComparable OrderByProperty<T>( String propertyName , T item ) where T : class
        {
            PropertyInfo[] propertyList;

            propertyList = GetInfo( item );

            //Here we get the value of that property of the passed in item and make sure
            //to type the object (Which is what GetValue returns) into an IComparable
            return (IComparable)propertyList.First( currentProperty => currentProperty.Name == propertyName ).GetValue( item , null );
        }
    }
}
